Namespace("sketch.ui.iphone");

(function(fwk, ui) {
    ui.iphone.GoogleMap = klass(fwk.UIElement, (function() {
        var onPropertyChanged = function(events) {
            var needRefresh = false;
            for (var i = 0; i < events.length; i++) {
                var event = events[i];
                switch (event.property) {
                    case "center":
                    case "mapType":
                        needRefresh = true;
                        break;
                }
            }
            if (needRefresh) {
                var that = this;
                var src = 'http://maps.googleapis.com/maps/api/staticmap?center=' +
                    this.center() +
                    '&zoom=14&size=320x480&maptype=' +
                    this.mapType() + '&sensor=false';
                var img = new Image();

                img.onload = function() {
                    that._mapImage = img;
                    that.invalidate();
                };

                img.onerror = function() {
                    that._mapImage = fwk.Resources["google_map"];
                    that.invalidate();
                };

                img.src = src;
            }
        };

        return {
            _constructor:function() {
                this.properties.createProperty('center', 'Map center', 'Brooklyn+Bridge,New+York,NY').useInModel().editorTemplate("#editor-textbox");
                this.properties.createProperty("mapType", "Map type", "roadmap")
                    .possibleValues({'roadmap':'Roadmap', 'satellite':'Satellite', 'hybrid':'Hybrid', 'terrain':'Terrain'})
                    .useInModel()
                    .editorTemplate("#editor-dropdown");
                this._mapImage = fwk.Resources["google_map"];

                this.properties.propertyChanged.bind(EventHandler(this, onPropertyChanged));
                this.properties.lockNotifications();
                this.width(320);
                this.height(480);
                this.center('Brooklyn+Bridge,New+York,NY');
                this.properties.unlockNotifications();
            },
            center:function(value) {
                return this.properties.center(value);
            },
            mapType:function(value) {
                return this.properties.mapType(value);
            },
            drawSelf:function(context) {
                var x = this.left(),
                    y = this.top(),
                    w = this.width(),
                    h = this.height();

                context.rectPath(x, y, w, h);
                context.clip();
                context.drawImage(this._mapImage, x, y);
            }
        };
    })());
})(sketch.framework, sketch.ui);